package com.hui.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.exception.UserException;
import com.hui.admin.service.FileService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        // 定义文件基础路径（可从配置文件注入，这里演示硬编码）
        String filePath = System.getProperty("user.dir") + "/files/";
        String realPath = filePath + fileName;

        // 检查文件是否存在
        if (!FileUtil.exist(realPath)) {
            throw new UserException(ErrorCodeEnum.FILE_NOT_EXIST); // 自定义异常或返回错误信息
        }

        // 获取文件字节流
        byte[] fileBytes = FileUtil.readBytes(realPath);

        // 设置响应头（解决中文文件名乱码）
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 写出到响应输出流
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(fileBytes);
            outputStream.flush();
        }
    }

    @Override
    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new UserException(ErrorCodeEnum.FILE_EMPTY);
        }

        String uploadPath = System.getProperty("user.dir") + "/files/";

        // 1. 确保上传目录存在
        File uploadDir = FileUtil.file(uploadPath);
        if (!uploadDir.exists()) {
            FileUtil.mkdir(uploadDir);
        }

        // 2. 构建唯一文件名（防止重复）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = FileUtil.extName(originalFilename);
        String newFileName = IdUtil.fastSimpleUUID() + "." + fileExtension;

        // 3. 写入文件到本地
        File dest = FileUtil.file(uploadDir, newFileName);

        try {
            FileUtil.writeFromStream(file.getInputStream(), dest);
        } catch (IOException e) {
            throw new UserException(ErrorCodeEnum.FILE_UPLOAD_FAILED);
        }

        // 4. 返回相对路径或 URL
        return "http://127.0.0.1:9090/api/file/download/" + newFileName;
    }

    @Override
    public Map<String, Object> wangEditorUpload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileExtension = FileUtil.extName(originalFilename);
        String newFileName = IdUtil.fastSimpleUUID() + "." + fileExtension;
        try {
            String uploadPath = System.getProperty("user.dir") + "/files/";
            FileUtil.writeBytes(file.getBytes(), uploadPath + newFileName);
        } catch (IOException e) {
            throw new UserException(ErrorCodeEnum.FILE_UPLOAD_FAILED);
        }
        String http = "http://127.0.0.1:9090/api/file/download/";
        Map<String, Object> map = new HashMap<>();
        map.put("errno", 0);
        map.put("data", CollUtil.newArrayList(Dict.create().set("url", http + newFileName)));
        return map;
    }

}
